<?php

namespace app\index\controller;

use app\index\model\Msg as ModelMsg;

class Msg extends Base
{
    public function list()
    {
        $this->logs('个人消息列表');
        $limit = input('limit') ?? 10;
        $list = ModelMsg::list($limit);
        return $list;
    }
    public function index()
    {
        $this->logs('个人消息视图');
        return view();
    }
    // 读取消息
    public function read()
    {
        $this->logs('阅读个人消息');
        $id = input('id');
        if (empty($id)) return error();
        $idArr = explode(',', $id);
        $isUserMsgId = [];
        for ($i = 0; $i < count($idArr); $i++) {
            if (is_numeric($idArr[$i])) {
                $msgHas = ModelMsg::where(['id' => $id, 'receiver_uid' => $this->user['user_id']])->findOrEmpty()->isEmpty();
                if (!$msgHas) array_push($isUserMsgId, $idArr[$i]);
            }
        }
        $data = ['status' => 1];
        $res = ModelMsg::whereIn('id', $isUserMsgId)->update($data);
        if ($res) return success();
        return error();
    }
    public function readAll()
    {
        $res = ModelMsg::where(['status' => 0, 'receiver_uid' => $this->user['user_id']])->update(['status' => 1]);
        if ($res) return success();
        return error();
    }
    public function del($id)
    {
        $this->logs('删除个人消息');
        if (empty($id)) return error('消息ID不能为空');
        $id = input('id');
        $idArr = explode(',', $id);
        $delId = [];
        for ($i = 0; $i < count($idArr); $i++) {
            $msgHas = ModelMsg::where(['id' => $id, 'receiver_uid' => $this->user['user_id']])->findOrEmpty()->isEmpty();
            if (!$msgHas) {
                array_push($delId, $idArr[$i]);
            }
        }
        $res = ModelMsg::whereIn('id', $delId)->delete();
        if ($res) return success();
        return error();
    }
}
